const express = require('express')
const router = express.Router()

const User = require('../../model/user.js')

// 加密
const bcrypt = require('bcrypt')

// 生成token
const jwt = require('jsonwebtoken')

// 验证token
const passport = require('passport')

const secretOrKey = require('../../config/keys.js')


// 头像设置
// const gravatar = require('gravatar')

router.get('/test', (req, res) => {
    res.send('kjdshfjk')
})

// 注册功能
router.post('/register', async(req, res) => {
    // console.log(req.body);

    // 查询数据库中是否邮箱已经注册
    let user = await User.findOne({ email: req.body.email })
    if (user) {
        return res.status(400).json('邮箱已被注册！')
    } else {

        const avatar = 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20171221%2F2a14e6b09df846a1908379c06045ba96.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1633007789&t=0f211fc0622d6f170af5212393947e83'

        const newUser = new User({
            username: req.body.username,
            email: req.body.email,
            avatar,
            password: req.body.password,
            role: req.body.role
        })


        bcrypt.genSalt(10, (err, salt) => {
            bcrypt.hash(newUser.password, salt, async(err, hash) => {
                if (err) throw err;
                newUser.password = hash
                try {
                    await newUser.save()
                    res.json({ message: 'ok', status: 200 })
                } catch {
                    res.status(404).json(err)
                }
            });
        });
    }
})

// 登录功能
router.post('/login', async(req, res) => {
    const email = req.body.email
    const password = req.body.password

    const user = await User.findOne({ email })
    if (!user) {
        return res.status(404).json('用户不存在')
    }

    const isTure = await bcrypt.compare(password, user.password)
    if (isTure) {
        const rule = {
            id: user.id,
            username: user.username,
            avatar: user.avatar,
            role: user.role
        }
        const secret = secretOrKey
            //rule表示传给passport的值
            //secret是key
            //{expiresIn:100000}表示过期时间单位是秒
        jwt.sign(rule, secret, { expiresIn: 3600 }, (err, token) => {
            return res.json({
                // success: true,
                // token: 'bearer ' + token,
                data: {
                    success: true,
                    token: 'bearer ' + token,
                },
                role: user.role,
                status: 200,
                message: 'OK'
            })
        });
    } else {
        return res.status(400).json('密码错误')
    }
})

// 验证token
router.get('/current', passport.authenticate("jwt", { session: false }), (req, res) => {
    res.json({
        id: req.user.id,
        username: req.user.username,
        email: req.user.email,
        role: req.user.role
    })
})


module.exports = router